package day20240904;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;

@WebServlet("/login")
public class MyHttpServlet extends HttpServlet {
    public Connection getConnection() throws SQLException, ClassNotFoundException {
        Class.forName("com.mysql.cj.jdbc.Driver");
        System.out.println("JDBC驱动加载成功！");
        String url = "jdbc:mysql://localhost:3306/users";
        String user = "root";
        String password = "lcw0909.";
        Connection connection = DriverManager.getConnection(url, user, password);
        return connection;
    }

    public boolean getSql(String username, String password) throws SQLException {

        try {
            // 加载数据库驱动
            // 注意：从JDBC 4.0开始，通常不需要显式加载JDBC驱动
            // Class.forName("com.mysql.cj.jdbc.Driver");

            // 创建数据库连接
            Connection conn = getConnection();

            // 创建SQL语句
            String sql = "SELECT * FROM table_users"; // 替换为你的表名和需要的列

            // 创建PreparedStatement
            PreparedStatement pstmt = conn.prepareStatement(sql);

            // 执行查询
            ResultSet rs = pstmt.executeQuery();

            // 处理查询结果
            while (rs.next()) {
                // 假设你的表有两列，一列是id（整型），一列是name（字符串）
                String name = rs.getString("username");
                String pass = rs.getString("password");
                if (name.equals(username) && pass.equals(password)) {
                    return true;
                }
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        return false;
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        System.out.println(username + "===" + password);
        System.out.println("MyHttpServlet.doGet");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /**
         * 1、创建数据库（username， password）
         * 2、连接数据库
         * 3、点击登录按钮后如果在数据库中匹配到对应的数据则返回true反之则输出false
         * 4、根据返回的bool来显示不同的界面
         *
         */
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        try {
            boolean sql = getSql(username, password);
            if (sql) {
                String yes = """
                        <html>
                        <body>
                        yes
                        </body>
                                                
                        </html>
                        """;
                PrintWriter writer = resp.getWriter();
                writer.write(yes);
            } else {
                String no = """
                                <html>
                        <body>
                       no
                        </body>
                                                
                        </html>                  
                        """;
                PrintWriter writer = resp.getWriter();
                writer.write(no);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }


    }

}
